#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int cnt = 0;
        ListNode* cur = head;
        while (cur) {
            cnt++;
            cur = cur->next;
        }
        if (cnt == n) {
            ListNode* t = head->next;
            delete head;
            return t;
        }
        int res = cnt - n + 1;
        int pos = 0;
        cur = head;
        ListNode* pre = nullptr;
        while (cur) {
            pos++;
            if (pos == res) {
                ListNode* t = cur->next;
                delete cur;
                pre->next = t;
                break;
            }
            pre = cur;
            cur = cur->next;
        }
        return head;

    }
};